package com.wangzhixuan.commons.config;

import com.google.common.collect.Maps;
import com.wangzhixuan.commons.Constant;
import com.wangzhixuan.commons.enums.CacheEnum;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;

import java.util.Map;

/**
 * redis缓存配置
 *
 * @author lixin
 */
@Configuration
@ConditionalOnProperty(value = "spring.redis.enable",havingValue = "true")
public class RedisConfig {
    @Bean
    public RedisCacheManager redisCacheManager(RedisConnectionFactory redisConnectionFactory) {
        String name = Constant.CONFIG_GROUP;
        Map<String, RedisCacheConfiguration> initCache = Maps.newHashMap();
        RedisCacheConfiguration cacheConfiguration = RedisCacheConfiguration.defaultCacheConfig();
        for (CacheEnum cacheEnum : CacheEnum.values()) {
            initCache.put(cacheEnum.getName(), cacheConfiguration.prefixKeysWith(name + ":" + cacheEnum.getName() + ":").entryTtl(cacheEnum.getCacheTime()));
        }
        return RedisCacheManager.builder(redisConnectionFactory).withInitialCacheConfigurations(initCache).build();
    }
}
